//
//  LBCategoryPopuView.m
//  AFNetworking
//
//  Created by luckyRoy on 2018/1/31.
//

#import "LBCategoryPopuView.h"
#import "LBCategorySelectedView.h"
#import "LBFacListView.h"
#import "LBNewCategoryMainView.h"
#import "UIColor+LBColor.h"
#import "NSString+LBString.h"
#import "LBCategoryPopuViewCell.h"
#import "Masonry.h"
#import "LBFacCustomCollectionViewFlowLayout.h"

#define WINDOW         [[UIApplication sharedApplication].delegate window]
static NSInteger const LBCategoryPopuViewTag = 12898796;

@interface LBCategoryPopuView ()

@property (nonatomic, strong) UIView *blackView;

@property (nonatomic, strong) LBCategorySelectedView *selectedView;

@property (strong, nonatomic) LBFacListView *facCollectionView;

@property (nonatomic, copy) LBCategoryPopuViewBlock complete;

@property (nonatomic, assign) LBCategoryPopuViewBlockType blockType;

@property (nonatomic, strong) NSMutableArray *listArray;

@property (nonatomic, strong) LBCategorySettingModel *model;

@property (nonatomic, strong) LBFacCustomCollectionViewFlowLayout *customLayout;

@property (nonatomic, assign) CGFloat maxListViewHeight;

@end

@implementation LBCategoryPopuView

- (instancetype)initWithFrame:(CGRect)frame
                     theModel:(LBCategorySettingModel *)model
{
    self = [super initWithFrame:frame];
    if (self) {
        self.model = model;
        [self createAllView];
    }
    return self;
}

- (void)createAllView
{
    self.blackView = [[UIView alloc]initWithFrame:self.frame];
    
    self.blackView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
    __weak __typeof(&*self)weakSelf = self;
    self.selectedView = [[LBCategorySelectedView alloc]initWithFrame:CGRectZero isSingleSelected:self.model.isSingleSelected complete:^(LBCategorySelectedViewBlockType blockType){
        if (LBCategorySelectedViewBlockTypeLooking == blockType) {
            [weakSelf dimiss];
        } else {
            [weakSelf dimiss];
            if (weakSelf.complete) {
                weakSelf.complete(LBCategoryPopuViewBlockTypeComplete);
            }
        }
    }];
    
    [self addSubview:self.blackView];
    
    [self addSubview:self.selectedView];
    
    [self addSubview:self.facCollectionView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dimiss)];
    [self.blackView addGestureRecognizer:tapGesture];
    
    self.selectedView.backgroundColor = [UIColor whiteColor];
    self.facCollectionView.backgroundColor = [UIColor whiteColor];
    
    CGFloat defaultHeight = 46;
    [self.selectedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(defaultHeight);
    }];
    [self.facCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.selectedView.mas_top);
        make.height.mas_equalTo(0);
    }];
    
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.facCollectionView.mas_top);
        make.height.mas_equalTo(10);
    }];
}

- (void)dimiss
{
    [self.class dimiss];
}

- (void)reloadByArray:(NSArray *)listArray
{
    [self.facCollectionView setCellModelArray:listArray];
    [self.facCollectionView reloadListView];
    [self layoutIfNeeded];
    
    CGFloat listViewHeight = self.customLayout.contentHeight;
    
    if (listViewHeight > self.maxListViewHeight) {
        listViewHeight = self.maxListViewHeight;
    }
    
    listViewHeight += 10;//加边距

    [self.facCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(listViewHeight);
    }];
    [self.selectedView reloadView:self.listArray isUp:NO];
}

+ (LBCategoryPopuView *)findPopuViewByModel:(LBCategorySettingModel *)model
{
    UIView *oneView = [WINDOW viewWithTag:LBCategoryPopuViewTag];
    if (oneView && [oneView isKindOfClass:[LBCategoryPopuView class]]) {
        return (LBCategoryPopuView *)oneView;
    }
    LBCategoryPopuView *popuView = [[LBCategoryPopuView alloc]initWithFrame:WINDOW.bounds theModel:model];
    popuView.tag = LBCategoryPopuViewTag;
    return popuView;
}

+ (BOOL)isPopuViewExist
{
    BOOL isExist = NO;
    UIView *oneView = [WINDOW viewWithTag:LBCategoryPopuViewTag];
    if (oneView && [oneView isKindOfClass:[LBCategoryPopuView class]]) {
        isExist = YES;
    }
    return isExist;
}

+ (void)showByType:(LBCategoryPopuViewType)popuType
        listModels:(NSArray *)listModels
             model:(LBCategorySettingModel *)model
          complete:(LBCategoryPopuViewBlock)complete
{
    LBCategoryPopuView *popuView = [self findPopuViewByModel:model];
    
    popuView.complete = complete;
    
    [WINDOW addSubview:popuView];
    
//    CGFloat totalHeight = WINDOW.bounds.size.height;
//    CGFloat totalWidth = WINDOW.bounds.size.height;
//
    CGFloat defaultHeight = 46;
    
    CGFloat submitButtonHeight = 48;
    
    popuView.listArray = [NSMutableArray arrayWithArray:listModels];
    
//    CGFloat listViewHeight = [LBCategoryModelManager heightForSelectedListView:listModels];
    
    [popuView reloadByArray:popuView.listArray];
    
    CGFloat listViewHeight = popuView.customLayout.contentHeight;
    
    CGFloat maxHeight = [[UIScreen mainScreen] bounds].size.height/2.0;;
    
    CGFloat listViewMaxHeight = (maxHeight - defaultHeight - submitButtonHeight);
    
    if (listViewHeight > listViewMaxHeight) {
        listViewHeight = listViewMaxHeight;
    }
    
    popuView.maxListViewHeight = listViewHeight;
    
    listViewHeight += 10;//加边距
    
    
    
//    [listModels enumerateObjectsUsingBlock:^(LBCategoryModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
//        model.isChosedCell = YES;
//        model.isEdiotr = YES;
//    }];
//
    [popuView.selectedView reloadView:listModels isUp:NO];
    
    [popuView.facCollectionView setHidden:YES];
    
    if (LBCategoryPopuViewTypeOnlySelected == popuType) {
//        [popuView.submitButton setHidden:YES];
//        CGFloat selecteViewY = (totalHeight - defaultHeight - listViewHeight);
//        popuView.selectedView.frame = CGRectMake(0,selecteViewY,totalWidth, defaultHeight);
//        popuView.facCollectionView.frame = CGRectMake(0, CGRectGetMaxY(popuView.selectedView.frame), totalWidth, listViewHeight);
        [popuView.facCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(listViewHeight);
        }];
    } else if (LBCategoryPopuViewTypeSaveBooking == popuType) {
        [popuView.facCollectionView setHidden:NO];
//        CGFloat selecteViewY = (totalHeight - defaultHeight - listViewHeight - submitButtonHeight);
//        popuView.selectedView.frame = CGRectMake(0,selecteViewY,totalWidth, defaultHeight);
//        popuView.facCollectionView.frame = CGRectMake(0, CGRectGetMaxY(popuView.selectedView.frame), totalWidth, listViewHeight);
//        popuView.submitButton.frame = CGRectMake(0, CGRectGetMaxY(popuView.facCollectionView.frame), totalWidth, submitButtonHeight);
        [popuView.facCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(listViewHeight);
        }];

    } else if (LBCategoryPopuViewTypeNextStep == popuType) {
        [popuView.facCollectionView setHidden:NO];
//        CGFloat selecteViewY = (totalHeight - defaultHeight - listViewHeight - submitButtonHeight);
//        popuView.selectedView.frame = CGRectMake(0,selecteViewY,totalWidth, defaultHeight);
//        popuView.facCollectionView.frame = CGRectMake(0, CGRectGetMaxY(popuView.selectedView.frame), totalWidth, listViewHeight);
//        popuView.submitButton.frame = CGRectMake(0, CGRectGetMaxY(popuView.facCollectionView.frame), totalWidth, submitButtonHeight);
        [popuView.facCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(listViewHeight);
        }];
    }
    
//    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
//        popuView.blackView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
//    } completion:^(BOOL finished) {
//    }];
}

+ (void)dimiss
{
    if ([self isPopuViewExist]) {
        LBCategoryPopuView *popuView = [self findPopuViewByModel:nil];
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            popuView.blackView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [popuView removeFromSuperview];
        }];
    }
}

#pragma mark - click

- (void)submitButtonClick:(UIButton *)senter
{
    if (self.complete) {
        self.complete(LBCategoryPopuViewBlockTypeComplete);
    }
    [self.class dimiss];
}

#pragma mark - setter

#pragma mark - getter

- (LBFacCustomCollectionViewFlowLayout *)customLayout
{
    if (!_customLayout) {
        _customLayout = [[LBFacCustomCollectionViewFlowLayout alloc]init];
    }
    return _customLayout;
}

- (LBFacListView *)facCollectionView
{
    if (!_facCollectionView) {
        __weak __typeof(&*self)weakSelf = self;
        CGFloat width = ([[UIScreen mainScreen] bounds].size.width - 20);
        _facCollectionView = [[LBFacListView alloc]initCollectionViewWithFlowLayout:self.customLayout frame:CGRectMake(0, 0, width, 200) cellName:@"LBCategoryPopuViewCell" maxItemsOneLine:4 click:^(NSIndexPath *indexPath) {
            if (indexPath.row < weakSelf.listArray.count) {
                LBCategoryModel *model = weakSelf.listArray[indexPath.row];
                [weakSelf.listArray removeObjectAtIndex:indexPath.row];
                [weakSelf.model removeCategoryModel:model currentPage:LBCategorySettingPageTypeHomePage];
                [weakSelf.facCollectionView.collectionView performBatchUpdates:^{
                    [weakSelf.facCollectionView.collectionView deleteItemsAtIndexPaths:@[indexPath]];
                } completion:^(BOOL finished) {
                    [weakSelf reloadByArray:weakSelf.listArray];
                    if (weakSelf.complete) {
                        weakSelf.complete(LBCategoryPopuViewBlockTypeDel);
                    }
                }];
            }
        } otherClick:nil];
        [_facCollectionView customCollectionCellWithSize:^CGSize(NSIndexPath *indexPath) {
            
            LBCategoryModel *model = weakSelf.facCollectionView.cellModelArray[indexPath.row];

            return CGSizeMake([LBCategoryPopuViewCell realCellWidthByModel:model],[LBCategoryPopuViewCell fac_heightForViewByModel:nil]);
        }];
    }
    return _facCollectionView;
}

@end
